package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtConfigProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.logging.LogLevel;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserInterceptor  implements HandlerInterceptor {
    @Autowired
    private JwtConfigProperties jwtConfigProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       if(!( handler instanceof HandlerMethod)){
           return  true;
       }
        String token = request.getHeader("authorization");
       //如果token为空直接返回401
        if (token==null){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //解析jwt
        Claims claims = JwtUtil.parseJWT(jwtConfigProperties.getBase64EncodedSecretKey(), token);
        log.info("claims:{}",claims);
        if (claims==null){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //取出jwt中的数据
        Long userId= Long.valueOf(claims.get(Constants.JWT_USERID).toString());
        if (userId==null){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        log.info("{}--------------------------------------",claims.get(Constants.JWT_USERID));
        UserThreadLocal.set(userId);
        return  true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      UserThreadLocal.remove();
    }
}
